/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008 www.pretty-tools.com
 */

var gProgressMeter1, gProgressMeter2;
var images;
var destination;
var idx = 0;

function onProgress(progress, progressMax)
{
    if (progress == progressMax)
        onSaveComplete();
}

function saveImage(src, dest)
{
    var persist = yrprxComponentsFactory.createWebBrowserPersist();

    persist.progressListener = onProgress;

    persist.saveURI(src, dest);
}

function saveNextImage()
{
    try
    {
        while (idx < images.length && !images[idx])
            idx++;

        if (idx >= images.length)
        {
            yrprxBrowser.closeWindow();
            return;
        }

        var imgSource = images[idx++];
        if (0 != imgSource.indexOf("javascript:"))
            saveImage(imgSource, wsshSaveImageHelper.getImageFileName(destination, imgSource));
        else
        {
            var urlResolver = null;
            eval(imgSource.replace("javascript:", "urlResolver="));
            imgSource = urlResolver;

            imgSource(function(url) {
                if (!url)
                    saveNextImage();
                else
                    saveImage(url, wsshSaveImageHelper.getImageFileName(destination, url));
            });
        }

    }
    catch(ex)
    {
        var logger = yrprxFactory.createLogger("SaveImagesProgressDialog.js");
        if (logger.enabled) logger.error("saveNextImage: ", ex);
    }
}

function onSaveComplete()
{
    try
    {
        gProgressMeter1.style.width= "" + (100 * idx / images.length) + "%";
        gProgressMeter2.style.width= "" + (100 - 100 * idx / images.length) + "%";
        if (idx == images.length)
            setTimeout("yrprxBrowser.closeWindow()", 0);
        else
            setTimeout(saveNextImage, 0);
    }
    catch(ex)
    {
        var logger = yrprxFactory.createLogger("SaveImagesProgressDialog.js");
        if (logger.enabled) logger.error("onSaveComplete: ", ex);
    }
}

function onLoad()
{
    try
    {
        if (!("arguments" in window) || !window.arguments.length)
            yrprxBrowser.closeWindow();

        gProgressMeter1 = document.getElementById("progressmeter1");
        gProgressMeter2 = document.getElementById("progressmeter2");

        images = window.arguments[0];
        destination = window.arguments[1];

        saveNextImage();
    }
    catch(ex)
    {
        var logger = yrprxFactory.createLogger("SaveImagesProgressDialog.js");
        if (logger.enabled) logger.error("onLoad: ", ex);
    }
}

function onKeyPress()
{
    try
    {
        if (27 == window.event.keyCode)
            yrprxBrowser.closeWindow();
    }
    catch(ex)
    {
        var logger = yrprxFactory.createLogger("SaveImagesProgressDialog.js");
        if (logger.enabled) logger.error("onKeyPress: ", ex);
    }
}
